package processes

import (
	"fmt"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/constants"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/message"
)

var smsProcess SmsProcess

type SmsProcess struct {
	smsList []message.SmsMsg
}

func init() {
	smsProcess = SmsProcess{}
}

func (sp *SmsProcess) SendGroupMsg(content string) (err error) {
	// 创建Message结构体
	msg := message.Message{}

	// 设置Message类型
	msg.SetType(constants.MSG_TYPE_SMS_MSG)

	// 创建发送的消息
	var smsMsg message.SmsMsg
	smsMsg.Content = content
	smsMsg.Sender = curUser.User

	err = msg.SetData(smsMsg)
	if err != nil {
		fmt.Println("SendGroupMsg SetData fail:", err)
		return
	}
	curUser.Conn.SetMsg(msg)
	_, err = curUser.Conn.Send()
	if err != nil {
		fmt.Println("SendGroupMsg Send fail:", err)
		return err
	}
	sp.smsList = append(sp.smsList, smsMsg)
	return
}

func (sp *SmsProcess) ReceiveMsg(smsMsg message.SmsMsg) {
	sp.smsList = append(sp.smsList, smsMsg)
	fmt.Printf("%s：%s\n", smsMsg.Sender.UserName, smsMsg.Content)
}

func (sp *SmsProcess) OutputAllMsg() {
	for _, smsMsg := range sp.smsList {
		senderName := smsMsg.Sender.UserName
		if smsMsg.Sender.UserId == curUser.UserId {
			senderName = senderName + "(自己)"
		}
		fmt.Printf("%s：%s\n", senderName, smsMsg.Content)
	}
}
